package com.spring.iosservice.web.service.impl;

import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.interceptor.TransactionAspectSupport;

import com.aliyun.oss.OSSClient;
import com.aliyun.oss.model.ObjectMetadata;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.spera.aliyunContent.AliyunContent;
import com.spera.aliyunUtil.CreateOSSClient;
import com.spera.genutil.SpUtil;
import com.spring.api.web.model.Enregister;
import com.spring.common.web.service.CommonService;
import com.spring.courseapi.web.dao.GameCourseMapper;
import com.spring.courseapi.web.requestModel.Register;
import com.spring.courseapi.web.service.GameService;
import com.spring.iosservice.web.dao.IPadApiMapper;
import com.spring.iosservice.web.model.BuzProduct;
import com.spring.iosservice.web.model.EnregisterJson;
import com.spring.iosservice.web.service.IPadApiService;
import com.spring.security.core.util.ApplicationUtils;
import com.spring.security.core.util.UDate;
import com.spring.security.web.model.BaseResult;
import com.spring.tools.MyTools;
import com.sso.api.web.dao.SsoMapper;
import com.sso.api.web.model.RequestUser;
import com.sso.api.web.model.SsoFamily2;

import sun.misc.BASE64Decoder;

@Service
public class IPadApiServiceImpl implements IPadApiService{
	
	@Resource private IPadApiMapper iPadApiMapper;
	@Resource private SsoMapper ssoMapper;
	@Resource private GameService gameService;
	@Resource private CommonService commonService;
	@Resource
	private GameCourseMapper gameCourseMapper;	
	

	@Override
	public List<BuzProduct> buzProduct(String kids_parkId) {
		return iPadApiMapper.buzProduct(kids_parkId);
	}

	@Override
	public BaseResult signOff(String user_id, String username,
			String enregisterId, String fileid) {
		Map<String,Object> parm = Maps.newHashMap();
		parm.put("user_id", user_id);
		parm.put("username", username);
		parm.put("enregisterId", enregisterId);
		parm.put("fileid", fileid);
		int checkCanSignOff = iPadApiMapper.checkCanSignOff(parm);
		BaseResult ret = new BaseResult();
		//不可签字确认状态
		if(checkCanSignOff==0){
			ret.setStatus("0").setMsg("未找到相关记录，请确认登记状态");
		}else{
			int hasSuccess = iPadApiMapper.signOff(parm);
			if(hasSuccess==0){
				ret.setStatus("0").setMsg("操作失败");
			}
		}
		
		return ret;
	}

	@Override
	public BaseResult signIn(String user_id, String username,
			String enregisterIds) {
		Map<String,Object> parm = Maps.newHashMap();
		parm.put("user_id", user_id);
		parm.put("username", username);
		BaseResult ret = new BaseResult();
		String[] enregisterIdArr = enregisterIds.split(",");
		int wrang = 0;
		if(enregisterIdArr.length>0){
			for(String enregisterId:enregisterIdArr){
				parm.put("enregisterId", enregisterId);
				int i= iPadApiMapper.checkCanSignIn(parm);
				//不可确认进场状态
				if(i==0){
					wrang++;
				}else{
					int hasSuccess = iPadApiMapper.signIn(parm);
					if(hasSuccess==0){
						wrang++;
					}
				}
			}
		}
		if(wrang>0){
			ret.setStatus("0").setMsg("有学生家长未刷指纹或密码，请刷新并确认");
		}
		return ret;
	}

	@Override
	public BaseResult enregister(Enregister enregister) {
		//登记非注册客户时需要的信息
		Register register = getRegister(enregister);
		BaseResult ret = null;
		try {
//			HashMap<String,Object> parm = Maps.newHashMap();
//			parm.put("phone", enregister.getPhone());
//			int hasIn = ssoMapper.getUserCountByPhone(parm);
			int hasIn = 0;
//			if(hasIn>0){//手机用户已存在
			if(StringUtils.isNotBlank(enregister.getcUserID())){
//				if(StringUtils.isBlank(enregister.getGuardianId())){
//					ret = new BaseResult("0","监护人编号可为空");
//					return ret;
//				}
				if(StringUtils.isBlank(enregister.getcFamilyId())){
					ret = new BaseResult("0","家庭编号不可为空");
					return ret;
				}
				
				//如果家长编号为空，则新增家长
				if(StringUtils.isBlank(enregister.getGuardianId())){
					register = getGuardianRegister(enregister);
					ret = addGuardian(enregister,register);
					if("0".equals(ret.getStatus())){
						return ret;
					}
					//根据新注册的用户信息返回用户id，并和中文匹配
					List<Map<String,Object>> retM = (List<Map<String,Object>>)ret.getDataset();
					String username = "";
					for(Map<String,Object> one:retM){
						username = ApplicationUtils.Object2String(one.get("realName"));
						//匹配监护人id
						if(enregister.getGuardianName().equalsIgnoreCase(username)){
							enregister.setGuardianId(ApplicationUtils.Object2String(one.get("c_user_id")));
						}
					}
				}
				

				if(StringUtils.isBlank(enregister.getGuardianId())){
					ret = new BaseResult("0","监护人编号不可为空，或新增监护人信息失败，请检查手机号是否重复");
					return ret;
				}
				
				//如果小孩编号为空，则新增小孩
				if(StringUtils.isBlank(enregister.getBabyId())){
					register = getBabyRegister(enregister);
					ret = addBaby(enregister,register);
					if("0".equals(ret.getStatus())){
						return ret;
					}
					//根据新注册的用户信息返回用户id，并和中文匹配
					List<Map<String,Object>> retM = (List<Map<String,Object>>)ret.getDataset();
					String username = "";
					for(Map<String,Object> one:retM){
						username = ApplicationUtils.Object2String(one.get("realName"));
						//匹配小孩id
						if(enregister.getBabyName().equalsIgnoreCase(username)){
							enregister.setBabyId(ApplicationUtils.Object2String(one.get("c_user_id")));
						}
					}
				}
				
				if(StringUtils.isBlank(enregister.getBabyId())){
					ret = new BaseResult("0","宝宝编号不可为空，或新增宝宝信息失败");
					return ret;
				}
				
				HashMap<String,Object> parm_phone = Maps.newHashMap();
				parm_phone.put("phone", enregister.getGuardianPhone());
				parm_phone.put("finger", "check");
				hasIn = ssoMapper.getUserCountByPhone(parm_phone);
				if(hasIn==0){//未录入指纹
//					ret = new BaseResult("0","请先补录指纹");
//					return ret;
					enregister.setIsRegisteredFinger("0");
				}else{//指纹已录入
					enregister.setIsRegisteredFinger("1");
				}
				
				//存照片
				if(enregister.getGuardianPicUrl().contains("data:image")&&enregister.getGuardianPicUrl().contains(";base64")){//base64格式
					String photo = updateBase64File(enregister.getGuardianPicUrl(),enregister.getGuardianId());
					enregister.setGuardianPicUrl(photo);
				}
				
				if(enregister.getBabyPicUrl().contains("data:image")&&enregister.getBabyPicUrl().contains(";base64")){//base64格式
					String photo = updateBase64File(enregister.getBabyPicUrl(),enregister.getBabyId());
					enregister.setBabyPicUrl(photo);
				}
				//登记
				enregister.setId(ApplicationUtils.randomUUID());
				int isSuccess = iPadApiMapper.enregister(enregister);
				if(isSuccess>0){
					updateOrderEntrance(enregister.getOrderId());
					ret = new BaseResult("1","操作成功");
				}else ret = new BaseResult("0","操作失败");
			}else{//手机用户不存在
				
				if(StringUtils.isBlank(enregister.getGuardianName())){
					ret = new BaseResult("0","监护人不可为空");
					return ret;
				}
				//非注册客户注册
				ret = addBaby(enregister,register);
				if("0".equals(ret.getStatus())){
					return ret;
				}
//				ret=gameService.register(register,null);
				
				//根据新注册的用户信息返回用户id，并和中文匹配
				List<Map<String,Object>> retM = (List<Map<String,Object>>)ret.getDataset();
				String username = "";
				for(Map<String,Object> one:retM){
					username = ApplicationUtils.Object2String(one.get("realName"));
					//匹配小孩id
					if(enregister.getBabyName().equalsIgnoreCase(username)){
						enregister.setBabyId(ApplicationUtils.Object2String(one.get("c_user_id")));
					}
					//匹配家长id
					if(enregister.getGuardianName().equalsIgnoreCase(username)){
						enregister.setGuardianId(ApplicationUtils.Object2String(one.get("c_user_id")));
						enregister.setcFamilyId(ApplicationUtils.Object2String(one.get("c_familyID")));
					}
				}
				
				if(enregister.getGuardianPicUrl().contains("data:image")&&enregister.getGuardianPicUrl().contains(";base64")){//base64格式
					String photo = updateBase64File(enregister.getGuardianPicUrl(),enregister.getGuardianId());
					enregister.setGuardianPicUrl(photo);
				}
				
				if(enregister.getBabyPicUrl().contains("data:image")&&enregister.getBabyPicUrl().contains(";base64")){//base64格式
					String photo = updateBase64File(enregister.getBabyPicUrl(),enregister.getBabyId());
					enregister.setBabyPicUrl(photo);
				}
				
				if("1".equals(ret.getStatus())){
					//登记
					enregister.setId(ApplicationUtils.randomUUID());
					int isSuccess = iPadApiMapper.enregister(enregister);
					if(isSuccess>0) {
						//回写订单
						updateOrder(enregister.getOrderId(),enregister.getGuardianId(),enregister.getGuardianName());
						updateOrderEntrance(enregister.getOrderId());
						ret = new BaseResult("1","操作成功");
					}
					else ret = new BaseResult("0","操作失败");
				}
			}
		} catch (Exception e) {
			ret = new BaseResult("0","操作失败");
    		e.printStackTrace();
		}
		return ret;
	}
	
	//回写订单
	private void updateOrder(String orderId,String user_id,String real_name){
		Map<String,Object> parm = Maps.newHashMap();
		parm.put("orderId", orderId);
		parm.put("user_id", user_id);
		parm.put("real_name", real_name);
		iPadApiMapper.rebackOrderUser(parm);//回写订单信息
	}
	
	//回写是否登记标记（置为0  已登记）
	private void updateOrderEntrance(String orderId){
		Map<String,Object> parm = Maps.newHashMap();
		parm.put("orderId", orderId);
		iPadApiMapper.updateOrderEntrance(parm);//回写订单信息
	}
	
	private BaseResult addBaby(Enregister enregister,Register register) throws Exception{
		BaseResult ret = new BaseResult();
		if(StringUtils.isBlank(enregister.getSex())){
			ret = new BaseResult("0","新用户宝宝性别不可为空");
			return ret;
		}
		if(StringUtils.isBlank(enregister.getBirthday())){
			ret = new BaseResult("0","新用户宝宝生日不可为空");
			return ret;
		}
		if(StringUtils.isBlank(enregister.getBabyName())){
			ret = new BaseResult("0","宝宝姓名不可为空");
			return ret;
		}
		//非注册客户注册
		ret=register(register,null);
		return ret;
	}
	
	private BaseResult addGuardian(Enregister enregister,Register register) throws Exception{
		BaseResult ret = new BaseResult();
		if(StringUtils.isBlank(enregister.getPhone())){
			ret = new BaseResult("0","监护人手机号不可为空");
			return ret;
		}
		if(StringUtils.isBlank(enregister.getGuardianName())){
			ret = new BaseResult("0","监护人姓名不可为空");
			return ret;
		}
		//非注册客户注册
		ret=register(register,null);
		return ret;
	}
	
	public BaseResult register(Register register,String course_open_detailID) throws Exception {
		List<Map<String,Object>> retM = Lists.newArrayList();
		String familyID=null;
		String phone=null;
		BaseResult ret = new BaseResult("1","注册成功");
		//注册监护人
		if(register.getGuardians()!=null){
			for(int i=0;i<register.getGuardians().size();i++){
				RequestUser guardian=register.getGuardians().get(i);
				HashMap<String,Object> hmc=MyTools.checkIsNotNull(guardian.getPhone());
				if(hmc!=null){
					TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
					return new BaseResult("0","请输入必要参数");
				}
				phone=guardian.getPhone();
				guardian.setUserName(guardian.getPhone());
				if(i==0){//新建家庭id
					//新增家长信息
					Map<String, Object> hm=commonService.addUser(guardian);
					if(MyTools.ObjectToString(hm.get(ApplicationUtils.STATUS)).equals("0")){
						TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
						return new BaseResult("0",hm.get(ApplicationUtils.MSG).toString());
					}
					Map<String, Object> dataset=(Map<String, Object>)hm.get(ApplicationUtils.DATASET);
					//回写新增用户信息
					dataset.put("realName",guardian.getReal_name());
					retM.add(dataset);
					
					familyID=MyTools.ObjectToString(dataset.get("c_familyID"));
				}else{//调用第一个新增家长的家庭id
					guardian.setC_family_id(familyID);
					Map<String, Object> hm=commonService.addUser(guardian);
					Map<String, Object> dataset=(Map<String, Object>)hm.get(ApplicationUtils.DATASET);
					//回写新增用户信息
					dataset.put("realName",guardian.getReal_name());
					retM.add(dataset);
				}	
				
			}
		}
		
		if(register.getBabies()!=null){
			//新增宝宝信息
			for(int i=0;i<register.getBabies().size();i++){
				RequestUser baby=register.getBabies().get(i);		
				if(StringUtils.isBlank(baby.getC_family_id())&&StringUtils.isBlank(familyID)){
					continue;
				}
				
				if(StringUtils.isBlank(baby.getC_family_id())){
					baby.setC_family_id(familyID);			
				}
				
				//baby.setSex_code("0");
				baby.setC_role_id("0");
				//宝宝名(real_name)，性别，年龄->必输
				Map<String, Object> hm=commonService.addUser(baby);
				if(MyTools.ObjectToString(hm.get(ApplicationUtils.STATUS)).equals("0")){
					TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
					return new BaseResult("0",hm.get(ApplicationUtils.MSG).toString());
				}
				Map<String, Object> dataset=(Map<String, Object>)hm.get(ApplicationUtils.DATASET);
				//回写新增用户信息
				dataset.put("realName",baby.getReal_name());
				retM.add(dataset);
				
				HashMap<String, Object> hm2=new HashMap<String, Object>();
				String c_user_id=MyTools.ObjectToString(dataset.get("c_user_id"));
//				String baby_name=String.valueOf(jsonObject.get("baby_name"));
//				String phone2=String.valueOf(jsonObject.get("phone"));
				hm2.put("c_user_id", c_user_id);
				hm2.put("course_open_detailID", course_open_detailID);
				hm2.put("baby_name", baby.getReal_name());		
				hm2.put("phone", phone);	
				
				if(course_open_detailID!=null){
					int count=gameCourseMapper.appointCourseCheckCount(hm2);			
					if(count>0){
						return new BaseResult("0","请勿重复预约");
					}		
					int effect = gameCourseMapper.courseAppointment(hm2);		
					if(effect<1){
						return new BaseResult("0","预约失败");
					}
				}
			}
		}
		
		ret.setDataset(retM);
		
		return ret;
	}
	
	//根据登记信息组合用户注册信息
	private Register getRegister(Enregister enregister){
		Register register = new Register();
		List<RequestUser> babies = Lists.newArrayList();
		List<RequestUser> guardians = Lists.newArrayList();
		//宝宝信息
		RequestUser baby = new RequestUser();
		baby.setReal_name(enregister.getBabyName());
		baby.setSex_code(enregister.getSex());
		baby.setBirthday(enregister.getBirthday());
		//家长信息
		RequestUser guardian = new RequestUser();
		guardian.setPhone(enregister.getPhone());
		guardian.setReal_name(enregister.getGuardianName());
		babies.add(baby);
		guardians.add(guardian);
		register.setBabies(babies);
		register.setGuardians(guardians);
		return register;
	}
	
	//根据登记信息组合用户注册信息
	private Register getGuardianRegister(Enregister enregister){
		Register register = new Register();
		List<RequestUser> guardians = Lists.newArrayList();
		//家长信息
		RequestUser guardian = new RequestUser();
		guardian.setC_family_id(enregister.getcFamilyId());
		guardian.setPhone(enregister.getGuardianPhone());
		guardian.setReal_name(enregister.getGuardianName());
		guardians.add(guardian);
		register.setGuardians(guardians);
		return register;
	}
	
	//根据登记信息组合用户注册信息
	private Register getBabyRegister(Enregister enregister){
		Register register = new Register();
		List<RequestUser> babies = Lists.newArrayList();
		//宝宝信息
		RequestUser baby = new RequestUser();
		baby.setC_family_id(enregister.getcFamilyId());
		baby.setReal_name(enregister.getBabyName());
		baby.setSex_code(enregister.getSex());
		baby.setBirthday(enregister.getBirthday());
		babies.add(baby);
		register.setBabies(babies);
		return register;
	}

	@Override
	public int fingerHash(String c_user_id, String fingerHash,String enregisterId) {
		Map<String,Object> parm = Maps.newHashMap();
		parm.put("c_user_id", c_user_id);
		parm.put("fingerHash", fingerHash);
		int i = ssoMapper.updateFingerHash(parm);
		if(StringUtils.isNotBlank(enregisterId)){
			parm.put("enregisterId", enregisterId);
			iPadApiMapper.updateFingerStatus(parm);
		}
		return i;
	}

	@Override
	public int photoSrc(String c_user_id, String photoSrc) {
		Map<String,Object> parm = Maps.newHashMap();
		parm.put("c_user_id", c_user_id);
		parm.put("fingerHash", photoSrc);
		return ssoMapper.updatePhotoSrc(parm);
	}

	@Override
	public BaseResult enregisterFingers() {
		BaseResult ret = new BaseResult("1","查询成功");
		List<Map<String,Object>> retM = iPadApiMapper.enregisterFingers();
		List<Map<String,Object>> retN = Lists.newArrayList();
		if(retM!=null&&retM.size()>0){
			for(int i=0;i<retM.size();i++){
				Map<String,Object> oneM = retM.get(i);
				Map<String,Object> retH = ssoMapper.getUserByID(ApplicationUtils.Object2String(oneM.get("guardianId")));
				if(retH!=null
						&&ApplicationUtils.isNotNull(retH.get("photo_src"))
						&&ApplicationUtils.isNotNull(retH.get("finger_hash"))){
					retM.get(i).put("finger_hash", retH.get("finger_hash"));
					retM.get(i).put("phone", retH.get("phone"));
					retN.add(retM.get(i));
				}/*else{
					//移除没有指纹且没有头像照片的记录
					retM.remove(i);
				}*/
			}
		}
		ret.setDataset(retN);
		return ret;
	}

	@Override
	public BaseResult voiceTip() {
		BaseResult ret = new BaseResult("1","查询成功");
		List<Map<String,Object>> retM = iPadApiMapper.voiceTip();
		List<Map<String,Object>> retN = Lists.newArrayList();
		if(retM!=null&&retM.size()>0){
			retN.add(retM.get(0));
		}else{
			ret = new BaseResult("1","查询成功,暂无记录");
		}
		ret.setDataset(retN);
		return ret;
	}

	@Override
	public BaseResult voiceTipOver(String enregisterId) {
		BaseResult ret = new BaseResult();
		int i = iPadApiMapper.voiceTipOver(enregisterId);
		if(i==0){
			ret.setStatus("0").setMsg("更新失败");
		}
		return ret;
	}

	@Override
	public BaseResult confirmEnregister(String enregisterId,String confirmType,String userId,String userName) {
		BaseResult ret = new BaseResult();
		int i = 0;
		for(String type:confirmType.split(",")){
			Map<String,Object> parm = Maps.newHashMap();
			parm.put("enregisterId", enregisterId);
			parm.put("type", type);
			parm.put("confirmGuardianWorkerId", "oa用户，测试阶段不控制权限");
			parm.put("user_id", userId);
			parm.put("username", userName);
			i = iPadApiMapper.confirmEnregister(parm);
		}
		if(i==0){
			ret.setStatus("0").setMsg("更新失败");
		}
		return ret;
	}

	@Override
	public BaseResult pwdValidate(String phone) {
		BaseResult ret = new BaseResult();
//		if(StringUtils.isBlank(pwd)||StringUtils.isBlank(phone)){
//			ret.setStatus("0").setMsg("缺少认证参数，请确认");
//			return ret;
//		}
		Map<String,Object> parm = Maps.newHashMap();
//		parm.put("enregisterId", enregisterId);
		parm.put("phone", phone);
		List<EnregisterJson> retM = iPadApiMapper.queryEnregister(parm);
//		if(retM!=null&&retM.size()>0){
//			EnregisterJson retOne = retM.get(0);
//			String enregisterPwd = ApplicationUtils.Object2String(retOne.getExitConformPwd());
//			if(pwd.equals(enregisterPwd)){
//				ret.setDataset(retOne);
//			}else{
//				ret.setStatus("0").setMsg("密码验证失败");
//			}
//		}else{
//			ret.setStatus("0").setMsg("未找到记录");
//		}
		ret.setDataset(retM);
		return ret;
	}

	@Override
	public BaseResult needRegistrationProduct(String orderId) throws Exception{
//		BaseResult ret = new BaseResult();
		com.spring.iosservice.web.model.Order order = iPadApiMapper.needRegistrationProduct(orderId);
		if(order!=null){
		String c_user_id=order.getcUserID();
		
		if(c_user_id!=null){
			Map<String, Object> user=commonService.getFamilyDetail(null, null, null, c_user_id);
			
			List<SsoFamily2> list= (List<SsoFamily2>)user.get(ApplicationUtils.DATASET);
			if(list!=null&&list.size()>0){
				SsoFamily2 ssoFamily= list.get(0);				
				order.setSsoFamily(ssoFamily);
			}
		  }
		}
		return new BaseResult("1","查询成功",order);
	}
	
	
	public String updateBase64File(String formImgData, String c_user_id) throws Exception {
		String photo_src = "";
		Map<String, Object> m = Maps.newHashMap();

        Map<String, Object> parm = new HashMap<String, Object>();
        
        MyTools.checkIsNotNull(formImgData,c_user_id);
        
        String[] strlist=formImgData.split(",");
        
        if(strlist.length<2){
    		return "";
        }

        byte[] buffer = new BASE64Decoder().decodeBuffer(strlist[1]);
        
        ByteArrayInputStream bais=new ByteArrayInputStream(buffer);
        
        photo_src=imageFileUpOss(AliyunContent.fileBucket, "folder"+"/" + UDate.getDate() + "/"+ ApplicationUtils.randomUUID()+".jpg", bais,(long)buffer.length);
        
//        System.out.println(photo_src);
        
        parm.put("c_user_id", c_user_id);
        parm.put("photo_src", photo_src);
        
        int effect=ssoMapper.updateUserPhoto(parm);
        
        return photo_src;
	}
	
	 public String imageFileUpOss(String bucketName, String key, InputStream fis,Long fileSize)
	            throws Exception {
    	OSSClient client = CreateOSSClient.getInstance().getOSSClient();
        ObjectMetadata objectMeta = new ObjectMetadata();
        objectMeta.setContentLength(fileSize);
        // 可以在metadata中标记文件类型
        objectMeta.setContentType("image/jpeg");
       
        client.putObject(bucketName, key, fis, objectMeta);
        return "http://" + bucketName + ".img-cn-hangzhou.aliyuncs.com/" + key;
    }

	/**
	 * 判断语音是否存在
	 */
	@Override
	public BaseResult getNoAudioBaby() {
		BaseResult ret = new BaseResult();
		List<Map<String,Object>> retL = ssoMapper.getNoAudioBaby(null);
		if(retL!=null&&retL.size()>0){
			ret.setDataset(retL.get(0));
		}
		return ret;
	}

	/**
	 * 更新用户语音
	 */
	@Override
	public BaseResult updateUserVoice(HttpServletRequest req,String babyId,String babyName,String mp3Url,String langType) {
		BaseResult ret = new BaseResult();
		//判断类型是否正确
		if(!"pth".equals(langType)&&!"yy".equals(langType)){
			ret.setStatus("0");
			ret.setMsg("类型不正确");
			return ret;
		}
		
		Map<String,Object> m = Maps.newHashMap();
		String ossId = fileTransOss(req,mp3Url);
		if(ApplicationUtils.isNotNull(ossId)){
			m.put("babyId", babyId);
			m.put("babyName", babyName);
			m.put("mp3Url", ossId);
			m.put("langType", langType);
			//先执行更新
			int retI = iPadApiMapper.updateUserVoice(m);
			//如果未被更新到，说明没有记录，则执行插入
			if(retI==0){
				retI = iPadApiMapper.insertUserVoice(m);
			}
			//操作一条记录成功则更新状态
			if(retI==1){
				ssoMapper.updateUserVoice(m);
			}
		}else{
			ret.setStatus("0");
			ret.setMsg("获取声音文件失败");
		}
		
		return ret;
	}
	
	private String fileTransOss(HttpServletRequest req,String file_url){
		String oss_id="";
		if(StringUtils.isNotBlank(file_url)){
			try{
				String filename = fileDownLoad(req,file_url);
				if(StringUtils.isNotBlank(filename)){
					File f = new File(req.getRealPath("/")+filename);
					FileInputStream fis = null;                 
	                fis = new FileInputStream(req.getRealPath("/")+filename);
//					ImputStreamObj imsObj = SpUtil.getMP3URL(file_url);
					oss_id = ApplicationUtils.randomUUID();
					String newfilename = "userVoice-"+ApplicationUtils.randomUUID()+".mp3";
//					String filePath = SpUtil.imageFileUpOss(AliyunContent.fileBucket,"user_voice/"+UDate.getDate()+"/"+newfilename, imsObj.getIms(),imsObj.getSize());
					String filePath = SpUtil.mp3FileUpOss(AliyunContent.fileBucket,"user_voice/"+UDate.getDate()+"/"+newfilename, fis,f.length());
					Map<String,Object> im = new HashMap<String,Object>();
					im.put("id", oss_id);
					im.put("bucket", AliyunContent.fileBucket);
					im.put("url", filePath);
					im.put("etag", "");
					im.put("key", "user_voice/"+UDate.getDate()+"/"+newfilename);
					im.put("token", "");
					im.put("file_type", "mp3");
					commonService.addOssFile(im);
					fis.close();
					f.delete();
				}
			}catch(Exception e){
				e.printStackTrace();
			}
		}
		
		return oss_id;
	}
	
	private String fileDownLoad(HttpServletRequest req,String mp3Url){
		String filename = ApplicationUtils.randomUUID()+".mp3";
		InputStream in;
		try {
			in = new URL(mp3Url).openConnection().getInputStream();
			FileOutputStream f = new FileOutputStream(req.getRealPath("/")+filename);
			byte [] bb=new byte[1024];
			int len;
			while( (len=in.read(bb))>0){
			  f.write(bb, 0, len);
			}
			f.close();
			in.close();
		} catch (MalformedURLException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		} 
		
		return filename;
	}

}
